package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.SignHelper;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 呐喊短信接口
 */
public class SmsApiNAHAN extends GateWayHttpAbstract
{

    public SmsApiNAHAN(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        Map<String,Object> params = Maps.newHashMap();
        try{
            String t = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
            params.put("account", paramsMaps.get("account"));
            params.put("password", paramsMaps.get("password"));
            params.put("phone", mt.getPhone());
            params.put("userid", paramsMaps.get("userid"));
            params.put("content",URLEncoder.encode(mt.getSmsContent(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("网关:{}, 响应:{}", this.gateWayID, e);
        }

        String json =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/mt", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), json);
        
        List<SMSSRMessage> resultList = Lists.newArrayList();
        
        SMSSRMessage message = initGatewayResultMessage(json, mt, "code");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        
        if(StringUtils.equals(message.getResult(), "F10199")) {

            Map map = (Map) JSON.parse(json);
            resultCode = String.valueOf(map.get("code"));
            resultMessage = String.valueOf(map.get("msg"));
            if(StringUtils.equals(resultCode, "0")) {
                taskid = String.valueOf(map.get("data"));
            }
        	message.setMsgkey(mt.getPhone());
            setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
        }
        
        resultList.add(message);
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {


        logger.info("{}网关推送状态报告:{}", gateWayID, text);
        JSONArray datas = JSON.parseArray(text);
        for(int i=0 ; i < datas.size() ;i++){
            JSONObject data = datas.getJSONObject(i);
            SMSRTMessage smsRtMessage = initSmsRtMessage(data.getString("messageId "), data.getString("phone "),data.getString("phone "),
                    data.getString("result"), "DELIVRD");
            rtList.add(smsRtMessage);

        }
        return new SmsHttpMsgResponse("ok");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
    	logger.info("{}网关推送用户上行:{}", gateWayID, text);
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("ok");
        JSONArray datas = JSON.parseArray(text);
        for(int i=0 ; i < datas.size() ;i++){
            JSONObject data = datas.getJSONObject(i);
            SMSMOMessage sMSMOMessage = new SMSMOMessage();
            sMSMOMessage.setGateWayID(gateWayID);
            sMSMOMessage.setMsgContent(data.getString("content"));
            sMSMOMessage.setMsgid(data.getString("messageId"));
            sMSMOMessage.setPhone(data.getString("phone"));
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
            sMSMOMessage.setUuid(UUID.randomUUID().toString());
            moList.add(sMSMOMessage);
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return null;
    }

    @Override
    public String queryDeliver(String jsonText) {
        return null;
    }
    
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("account",paramsMaps.get("account"));
        params.put("password",paramsMaps.get("password"));
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/balance" , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);

        JSONObject object = JSON.parseObject(result);
        if (StringUtils.equals("0",object.getString("code"))) {
            return  "余额：" + object.getString("data");
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
    /*	SmsApiZHAOYONGSMS api = new SmsApiZHAOYONGSMS("JIESMS", "{\"account\":\"lihua\",\"password\":\"llh@9988\",\"longSms\":\"\",\"apiUrl\":\"http://www.88dx.cn\",\"reportSecTime\":\"5\", \"deliverSecTime\":\"5\"}");
    	SMSMTMessage mt = new SMSMTMessage();
    	mt.setPhone("18268846802");
    	mt.setSmsContent("【千橡科技】验证码：123456，10分钟内有效，如非本人操作，请忽略！");
    	List<SMSSRMessage> list = api.doSend(mt);
    	System.out.println(JSON.toJSONString(list));*/
        String params = "{\"account\":\"yuanheng\",\"password\":\"yuanheng\",\"apiUrl\":\"http://101.132.124.105:8080/\"}";
        SmsApiNAHAN api = new SmsApiNAHAN("ZY",params);
        String balance = api.balance();
        System.out.println(balance);
    }
    
}